﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class Operator_ApprovedRequests : System.Web.UI.Page
{
    BankDataDataContext db = new BankDataDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("Operator"))
        {
            Response.Redirect("~/Account/Login.aspx");
        }
        else
        {
            SqlDataSource1.SelectParameters["OperatorId"].DefaultValue = getOperatorId().ToString();
        }
    }

    protected int getOperatorId()
    {
        var operators = from bankOperator in db.Operators where bankOperator.UserId == (Guid)Membership.GetUser().ProviderUserKey select bankOperator;
        return operators.First().OperatorId;
    }

    protected void RequestListGridView_SelectedIndexChanged(object sender, EventArgs e)
    {
        string creditRequestId = RequestListGridView.DataKeys[RequestListGridView.SelectedIndex]["CreditRequestId"].ToString();
        var requests = from request in db.CreditRequests where request.CreditRequestId == Convert.ToInt32(creditRequestId) select request;
        if (requests.First().RequestStatusId == 1)
        {
            Session.Add("requestId", creditRequestId);
            if (requests.First().UserProfile.userId != null)
            {
                Response.Redirect("~/Operator/AddContract.aspx");
            }
            else
            {
                Session.Add("profileId", requests.First().UserProfileId.ToString());
                Response.Redirect("~/Operator/ClientsCreateEdit.aspx");
            }
        }
        else
        {
            Response.Redirect("~/Operator/ApprovedRequests.aspx");
        }
    }
    protected void RequestListGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string creditRequestId = RequestListGridView.DataKeys[e.RowIndex]["CreditRequestId"].ToString();
        var requests = from request in db.CreditRequests where request.CreditRequestId == Convert.ToInt32(creditRequestId) select request;
        db.CreditRequests.DeleteOnSubmit(requests.First());
        db.SubmitChanges();
    }
    protected void RequestListGridView_DataBinding(object sender, EventArgs e)
    {
        SqlDataSource1.SelectParameters["OperatorId"].DefaultValue = getOperatorId().ToString();
    }
}